package com.net.j8583.field;

import com.net.j8583.Protocol8583;
import com.net.utils.BcdUtils;
import com.net.utils.ByteUtil;
import com.net.utils.MacUtils;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 *
 * Date: 13-11-15
 * Time: 13:41
 */
public class FieldMac extends AbstractField {

    private List<Integer> joinMacFields = new ArrayList<Integer>();

    public FieldMac(Integer... joinMacInfo) {
        super(8, true);
        for (Integer integer : joinMacInfo) {
            joinMacFields.add(integer);
        }
    }

    public void clearBytes() {
        reqSrcBytes = new byte[]{};
        reqEncodeByte = new byte[]{};
        reqSrcValue = "";
    }

    @Override
    public byte[] toByte() {
        if (!i8583Request.isNeedMac()) {
            clearBytes();
            return reqSrcBytes;
        }
        List<Byte> byteList = new ArrayList<Byte>();
        Map<Integer, Field> data = i8583Request.getRequestData();
        for (Integer fieldId : joinMacFields) {
            Field field = data.get(fieldId);
            byte[] macData = field.getReqSrcBytes();
            byteList.addAll(ByteUtil.byteArray2List(macData));
        }
        byte[] macSrcData = ByteUtil.list2ByteArray(byteList);
        String macData = MacUtils.doMacANSI_x99_asc(i8583Request.getZmk(), i8583Request.getZak(), macSrcData);
        byte[] macBytes = BcdUtils.hex2byte(macData.getBytes());
        reqEncodeByte = macBytes;
        reqSrcBytes = macBytes;
        return macBytes;
    }

    @Override
    public String getFieldType() {
        return VAR;
    }

    @Override
    public boolean isAutoFill() {
        return true;
    }

    @Override
    public int toValue(byte[] data, int index) {
        return 0;
    }

    @Override
    public void decode(ByteBuffer byteBuffer, Protocol8583 i8583Protocol) {
        ByteBuffer buffer = ByteBuffer.allocate(fieldLen);
        for (int i = 0; i < fieldLen; i++) {
            buffer.put(byteBuffer.get());
        }

        byte[] response = buffer.array();
        respSrcBytes = response;
        respSrcValue = byte2Str(response);
        respDecodeBytes = buffer.array();
        respDecodeValue = byte2Str(response);
    }
}
